package com.yisu.expressway.onedollar.activity;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.yisu.expressway.R;
import com.yisu.expressway.onedollar.OneDollarConstants;
import com.yisu.expressway.onedollar.model.RecentAnnouncedItem;
import com.yisu.expressway.onedollar.presenter.IRecentAnnouncedListPresenter;
import com.yisu.expressway.onedollar.presenter.impl.RecentAnnouncedListPresenterImpl;
import com.yisu.expressway.onedollar.utils.DateUtil;
import com.yisu.expressway.onedollar.view.IRecentAnnouncedListView;
import com.yisu.expressway.onedollar.widget.CountdownView;
import com.yisu.expressway.onedollar.widget.TitleView;
import com.yisu.expressway.ui.recyclerview.BaseRvAdapter;
import com.yisu.expressway.ui.recyclerview.DividerListItemDecoration;
import com.yisu.expressway.ui.recyclerview.PagingRecyclerView;
import com.yisu.expressway.ui.refresh.SuperSwipeRefreshLayout;
import com.yisu.expressway.utils.StringUtil;
import com.yisu.expressway.utils.ToastUtil;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Kaven on 2016/12/7.
 */
public class RecentAnnouncedListActivity extends BasicActivity
        implements IRecentAnnouncedListView, PagingRecyclerView.SampleActionListener {
    @Bind(R.id.recent_title_bar)
    protected TitleView mTitleView;
    @Bind(R.id.refreshLayout)
    protected SuperSwipeRefreshLayout mRefreshLayout;
    @Bind(R.id.rv_content)
    protected PagingRecyclerView mPagingRecyclerView;
    private IRecentAnnouncedListPresenter mPresenter;
    private AnimationDrawable mAnimation;
    private boolean isFreshEnable;
    private ImageView carImage;
    @Bind(R.id.empty)
    protected View mEmptyView;
    @Bind(R.id.empty_des)
    protected TextView mEmptyDesTv;
    @Bind(R.id.empty_action)
    protected TextView mEmptyActionTv;
    @Bind(R.id.empty_iv)
    protected ImageView mEmptyIv;
    @Override
    protected int getInflateLayoutId() {
        return R.layout.activity_recent_announced;
    }

    @Override
    protected void initPresenter() {
        mPresenter = new RecentAnnouncedListPresenterImpl(this, this);
        mPresenter.init();
    }

    @Override
    protected void releasePresenter() {
        if (mPresenter != null) {
            mPresenter = null;
        }
    }

    @Override
    protected void getIntentData(Intent intent) {

    }

    @Override
    protected void getSavedBundleData(Bundle bundle) {

    }

    @Override
    protected void initViews() {
        initFreshLayout();
        DividerListItemDecoration mListDivider = new DividerListItemDecoration(this,
                LinearLayoutManager.VERTICAL);
        mPagingRecyclerView.init(mListDivider, new LinearLayoutManager(this), this, 20);
        mEmptyActionTv.setVisibility(View.GONE);
        mEmptyIv.setVisibility(View.GONE);
    }

    private View createHeaderView() {
        View headerView = getLayoutInflater().inflate(R.layout.layout_head, null);
        carImage = (ImageView) headerView.findViewById(R.id.pb_view);
        return headerView;
    }

    private void initFreshLayout() {
        mRefreshLayout.setHeaderViewBackgroundColor(0xffefeff4);
        mRefreshLayout.setHeaderView(createHeaderView());
        mRefreshLayout.setTargetScrollWithLayout(true);
        mRefreshLayout
                .setOnPullRefreshListener(new SuperSwipeRefreshLayout.OnPullRefreshListener() {

                    @Override
                    public void onRefresh() {
                        mAnimation.start();
                        mPagingRecyclerView.refreshData();
                    }

                    @Override
                    public void onPullDistance(int distance) {
                        int index = distance / 25;

                        int resId = R.drawable.car_1;
                        switch (index) {
                            case 2:
                                resId = R.drawable.car_2;
                                break;
                            case 3:
                                resId = R.drawable.car_3;
                                break;
                            case 4:
                                resId = R.drawable.car_4;
                                break;
                            case 5:
                                resId = R.drawable.car_5;
                                break;
                            case 6:
                                resId = R.drawable.car_6;
                                break;
                            case 7:
                                resId = R.drawable.car_7;
                                break;
                            case 8:
                                resId = R.drawable.car_8;
                                break;
                            case 9:
                                resId = R.drawable.car_9;
                                break;
                            case 10:
                                resId = R.drawable.car_10;
                                break;
                        }
                        if (!isFreshEnable) {
                            carImage.setBackgroundResource(resId);
                        }

                    }

                    @Override
                    public void onPullEnable(boolean enable) {
                        isFreshEnable = enable;
                        if (enable) {
                            carImage.setBackgroundResource(R.color.colorTransparent);
                            carImage.setImageResource(R.drawable.car_frame);
                            mAnimation = (AnimationDrawable) carImage.getDrawable();
                        }
                    }
                });
    }

    @Override
    protected void bindEvents() {
        mTitleView.setOnTitleBarClickEvent(new TitleView.OnTitleBarClickEvent() {
            @Override
            public void onLeftClick(View view) {
                finish();
            }

            @Override
            public void onTitleClick(View view) {

            }

            @Override
            public void onRightClick(View view) {

            }
        });
    }

    @Override
    protected boolean isNeedLogin() {
        return false;
    }

    @Override
    protected void onLoginStateChange(boolean login) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected int getThemeId() {
        return R.style.OneDollarTheme;
    }

    @Override
    public void showToast(String toastMsg) {
        if (StringUtil.isNullOrEmpty(toastMsg)) {
            return;
        }
        ToastUtil.displayLongToastMsg(this, toastMsg);
    }

    @Override
    public void showLoadingDlg() {
        showLoading();
    }

    @Override
    public void dismissLoadingDlg() {
        dismissLoading();
    }

    @Override
    public void jump2CommodityPurchasePage(long commodityNo) {
        if (commodityNo < 0) {
            return;
        }
        GoodsPurchaseActivity.launch(this, commodityNo);
    }

    @Override
    public void fetchData(int start, int pageSize) {
        mPresenter.fetchMore(start, pageSize);

    }

    @Override
    public void refreshViews(boolean bSuc, String msg) {
        if (mAnimation != null) {
            mRefreshLayout.setRefreshing(false);
            mAnimation.stop();
            carImage.setImageResource(R.color.colorTransparent);
        }

        if (bSuc) {
            List<RecentAnnouncedItem> recentAnnouncedList = mPresenter.getRecentAnnouncedList();
            if (recentAnnouncedList == null || recentAnnouncedList.isEmpty()) {
                mEmptyView.setVisibility(View.VISIBLE);
                mRefreshLayout.setVisibility(View.GONE);
                mEmptyDesTv.setText(getString(R.string.one_dollar_empty_ordershow));
                return;
            }
            mRefreshLayout.setVisibility(View.VISIBLE);
            mEmptyView.setVisibility(View.GONE);
            mPagingRecyclerView.dataFetchDone(recentAnnouncedList);
        } else {
            mRefreshLayout.setVisibility(View.GONE);
            mEmptyView.setVisibility(View.VISIBLE);
            mEmptyDesTv.setText(getString(R.string.one_dollar_empty_net_error));
            mPagingRecyclerView.dataFetchFail(msg);
        }
    }

    @Override
    public BaseRvAdapter.SampleViewHolder createItemViewHolder(ViewGroup parent, int viewType) {
        View itemView = getLayoutInflater().inflate(R.layout.recent_announced_item_list, null);
        return new RecentAnnouncedViewHolder(itemView);
    }

    @Override
    public void bindData(BaseRvAdapter.SampleViewHolder _holder, int position, Object _item) {
        final RecentAnnouncedViewHolder holder = (RecentAnnouncedViewHolder) _holder;
        final RecentAnnouncedItem item = (RecentAnnouncedItem) _item;

        String goodspic = item.goodsPic;
        if (!TextUtils.isEmpty(goodspic)) {
            String[] split = goodspic.split(",");
            if (split.length > 0) {
                String picShow = split[0];
                Glide.with(this).load(picShow).asBitmap()
                        .placeholder(R.drawable.pic_loading)
                        .diskCacheStrategy(DiskCacheStrategy.ALL).centerCrop()
                        .animate(R.anim.fade_in_image).into(holder.mGoodsCoverIv);
            }
        } else {
            holder.mGoodsCoverIv.setImageDrawable(getResources().getDrawable(R.drawable.pic_loading));
        }
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                GoodsPurchaseActivity.launch(RecentAnnouncedListActivity.this, item.goodsNo);
            }
        });
        holder.mGoodsName.setText(item.goodsName);
        String format = String.format(getResources().getString(R.string.one_dollar_periods_num),
                item.periodsNum);
        holder.mPeriodsnumTv.setText(format);
        boolean announced = false;
        long time3 = 0;
        try {
            Date dateNow = DateUtil.stringToDate(mPresenter.getSystemTime(),
                    DateUtil.PATTERN_DATE_TIME);
            Date dateAnnouce = DateUtil.stringToDate(item.announcedTime,
                    DateUtil.PATTERN_DATE_TIME);
            if (dateAnnouce !=null && dateNow != null){
                announced = dateNow.after(dateAnnouce);
//                time3 = dateAnnouce.getTime() - dateNow.getTime();
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        holder.mCountdownLL.setVisibility(!announced ? View.VISIBLE : View.GONE);
        holder.mWinningRecodeLL.setVisibility(!announced ? View.GONE : View.VISIBLE);
        if (!announced) {
            holder.mRemainCv.setVisibility(View.GONE);
            holder.mRemainCv.start(time3);
            holder.mRemainCv.setOnCountdownEndListener(new CountdownView.OnCountdownEndListener() {
                @Override
                public void onEnd(CountdownView cv) {
                    cv.setEnabled(false);

                }
            });
            holder.mRemainCv.setOnCountdownIntervalListener(1000,
                    new CountdownView.OnCountdownIntervalListener() {

                        @Override
                        public void onInterval(CountdownView cv, long remainTime) {
                            if (remainTime > OneDollarConstants.COUNT_DOWN_TIME) {
                                holder.mRemainCv.setVisibility(View.GONE);
                            } else {
                                holder.mRemainCv
                                        .setVisibility(remainTime == 0 ? View.GONE : View.VISIBLE);
                            }
                        }
                    });
        } else {
            if (item.winningRecord != null) {
                holder.mWinnerTv.setText(
                        String.format(getResources().getString(R.string.one_dollar_announced_name),
                                item.winningRecord.userName));
                holder.mRecordJoinNumTv.setText(
                        String.format(getResources().getString(R.string.one_dollar_join_num),
                                item.winningRecord.joinNum));
                holder.mRecordLuckNumberTv.setText(
                        String.format(getResources().getString(R.string.one_dollar_luck_num),
                                item.winningRecord.luckyNum));
                holder.mRecordAnnouncetimeTv.setText(
                        String.format(getResources().getString(R.string.one_dollar_announced_time),
                                item.winningRecord.announcedTime));
            }

        }
        holder.mRootView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jump2CommodityPurchasePage(item.goodsNo);
            }
        });

    }

    class RecentAnnouncedViewHolder extends BaseRvAdapter.SampleViewHolder {
        @Bind(R.id.rootView)
        View mRootView;
        @Bind(R.id.iv_goods_cover)
        ImageView mGoodsCoverIv;
        @Bind(R.id.tv_goods_name)
        TextView mGoodsName;
        @Bind(R.id.tv_periodsnum)
        TextView mPeriodsnumTv;

        @Bind(R.id.ll_countdown)
        View mCountdownLL;
        @Bind(R.id.cv_remain)
        CountdownView mRemainCv;

        @Bind(R.id.ll_winningrecord)
        View mWinningRecodeLL;

        @Bind(R.id.tv_record_announcetime)
        TextView mRecordAnnouncetimeTv;
        @Bind(R.id.tv_record_winner)
        TextView mWinnerTv;
        @Bind(R.id.tv_record_joinnum)
        TextView mRecordJoinNumTv;
        @Bind(R.id.tv_record_lucknum)
        TextView mRecordLuckNumberTv;

        public RecentAnnouncedViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}
